package com.youtui.manager.interceptor;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;

import com.youtui.manager.annotation.DataSource;
import com.youtui.manager.datasource.DataSourceContextHolder;

/** 数据源aop */
public class DataSourceInterceptor {

	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
		Signature sig = pjp.getSignature();
		MethodSignature msig = null;
		if (!(sig instanceof MethodSignature)) {
			throw new IllegalArgumentException("该注解只能用于方法");
		}
		msig = (MethodSignature) sig;
		Object target = pjp.getTarget();
		Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());

		if (currentMethod.isAnnotationPresent(DataSource.class)) {
			DataSource dataSource = currentMethod.getAnnotation(DataSource.class);
			DataSourceContextHolder.setDbType(dataSource.value().getValue());
		}
		/** 目标方法执行 */
		Object obj = pjp.proceed();
		return obj;
	}

	public void doAfter(JoinPoint jp) throws Throwable {
		/** threadlocal清理datasource */
		DataSourceContextHolder.clearDbType();
	}

}
